package com.sg.business.management.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;

import com.sg.business.model.Organization;
import com.sg.business.resource.nls.Messages;
import com.sg.widgets.fileupload.FileDialog;

public class ImportProjectTemplate extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IStructuredSelection sel = (IStructuredSelection) HandlerUtil
				.getCurrentSelection(event);
		if (sel == null || sel.isEmpty()) {
			return null;
		}
		final Object org = sel.getFirstElement();
		if (!(org instanceof Organization)) {
			return null;
		}
		Shell shell = HandlerUtil.getActiveShell(event);
		FileDialog fileDialog = new FileDialog(shell, SWT.MULTI | SWT.CLOSE);
		final String text = Messages.get().IMPORT_PROJECTTEMPLATE;
		fileDialog.setText(text);

		String result = fileDialog.open();
		if (result == null) {
			return null;
		}
		final String[] serverFileNames = fileDialog.getFileNames();
		String[] clientFileNames = fileDialog.getClientFileNames();
		if (serverFileNames == null || serverFileNames.length == 0
				|| clientFileNames == null || clientFileNames.length == 0) {
			return null;
		}

		ImportProjectTemplateJob job = new ImportProjectTemplateJob(text);
		job.setOrganization((Organization) org);
		job.setServerFileNames(serverFileNames);
		job.setUser(true);
		job.schedule();

		return null;
	}


}
